package com.health.trans.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;

/**
 * @author nqlz
 */
@Slf4j
public class JobUtil {
    protected static JobLauncher jobLauncher;
    public static JobBuilderFactory jobBuilderFactory;
    public static StepBuilderFactory stepBuilderFactory;

    public JobUtil(JobLauncher jobLauncher, JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory) {
        JobUtil.jobLauncher = jobLauncher;
        JobUtil.jobBuilderFactory = jobBuilderFactory;
        JobUtil.stepBuilderFactory = stepBuilderFactory;
    }

    public static JobExecution execute(Job job) {
        //构建参数
        JobParameters jobParameters = new JobParametersBuilder()
                .addLong("time", System.currentTimeMillis())
                .toJobParameters();
        //执行任务
        JobExecution run = null;
        try {
            run = jobLauncher.run(job, jobParameters);
        } catch (Exception e) {
            ExceptionUtil.wrapRuntimeAndThrow(e.getMessage());
        }
        if (run.getExitStatus().equals(ExitStatus.FAILED)) {
            run.getAllFailureExceptions().forEach(j -> ExceptionUtil.wrapRuntime(j).printStackTrace());
        }
        return run;
    }

}
